﻿/*********************************************************
 * 开发人员：小兵
 * 创建时间：2012-8-30 14:39:59
 * 描述说明：
 * 
 * 更改历史：
 * 
 * *******************************************************/
namespace Mozlite.Components
{
    using System;
    using System.Web;
    using System.Data;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;

    /// <summary>
    /// 用户文件。
    /// </summary>
    public class UserFile
    {
        /// <summary>
        /// 初始化类。
        /// </summary>
        public UserFile() { }
        /// <summary>
        /// 初始化类。
        /// </summary>
        /// <param name="file">上传文件实例。</param>
        /// <param name="folderID">文件夹ID。</param>
        public UserFile(HttpPostedFileBase file, int folderID)
        {
            FileName = file.FileName;
            Extension = System.IO.Path.GetExtension(file.FileName).Trim('.');
            UserID = AppContext.Current.UserID;
            CreateDate = DateTime.Now;
            LastUpdateDate = DateTime.Now;
            this.ContentLength = file.ContentLength;
            ContentType = file.ContentType;
            this.File = file;
            this.FolderID = folderID;
        }

        /// <summary>
        /// 文件ID。
        /// </summary>
        public int FileID { get; set; }
        /// <summary>
        /// 用户ID。
        /// </summary>
        public int UserID { get; set; }
        /// <summary>
        /// 文件夹ID。
        /// </summary>
        public int FolderID { get; set; }
        /// <summary>
        /// 文件名称。
        /// </summary>
        public string FileName { get; set; }
        /// <summary>
        /// 扩展名。
        /// </summary>
        public string Extension { get; set; }
        /// <summary>
        /// 物理文件ID。
        /// </summary>
        public Guid StorageID { get; set; }
        /// <summary>
        /// 创建日期。
        /// </summary>
        public DateTime CreateDate { get; set; }
        /// <summary>
        /// 更新日期。
        /// </summary>
        public DateTime LastUpdateDate { get; set; }
        private StorageFile storageFile;
        /// <summary>
        /// 物理路径实例。
        /// </summary>
        public StorageFile StorageFile
        {
            get
            {
                if(storageFile == null)
                    storageFile = Database.ExecuteReader<StorageFile>("SELECT * FROM moz_FileStorages WHERE StorageID = @StorageID;", new { StorageID = this.StorageID });
                return storageFile;
            }
        }
        /// <summary>
        /// 文件大小。
        /// </summary>
        public long ContentLength { get; set; }
        /// <summary>
        /// 文档类型。
        /// </summary>
        public string ContentType { get; set; }
        /// <summary>
        /// 上传文件实例。
        /// </summary>
        public HttpPostedFileBase File { get; private set; }
        /// <summary>
        /// 将文件上传到目录中。
        /// </summary>
        /// <returns>返回执行结果。</returns>
        public bool Save()
        {
            string path = Cores.GetNewTempPath();
            this.File.SaveAs(path);
            string md5 = Cores.HashFile(path);
            var storage = new StorageFile { MD5 = md5, ContentLength = File.ContentLength, ContentType = File.ContentType };
            if (System.IO.File.Exists(storage.Path))
                System.IO.File.Delete(path);
            else
                System.IO.File.Move(path, storage.Path);

            return Database.BeginTransaction<bool>(transaction =>
            {
                try
                {
                    storage.Save();
                }
                catch
                {
                    System.IO.File.Delete(storage.Path);
                    transaction.Rollback();
                }
                this.StorageID = storage.StorageID;
                return transaction.ExecuteNonQuery(@"INSERT INTO moz_Users_Files(FileName, Extension, CreateDate, LastUpdateDate, StorageID, FolderID, UserID)VALUES(@FileName, @Extension, GETDATE(), GETDATE(), @StorageID, @FolderID, @UserID);", new
                {
                    FileName = this.FileName,
                    Extension = this.Extension,
                    StorageID = this.StorageID,
                    FolderID = this.FolderID,
                    UserID = this.UserID
                });
            });
        }
        /// <summary>
        /// 访问文件地址。
        /// </summary>
        public string Url
        {
            get
            {
                return Cores.GetUrl("filestorages?classid=" + FileID + "&name=" + HttpUtility.UrlEncode(FileName));
            }
        }
        private string path;
        /// <summary>
        /// 文件物理路径。
        /// </summary>
        public string Path
        {
            get
            {
                if (path == null && this.StorageFile != null)
                    path = this.StorageFile.Path;
                return path;
            }
        }

        /// <summary>
        /// 文件物理路径。
        /// </summary>
        public string GetPath(int width, int height)
        {
            if (this.StorageFile == null)
                return null;
            var md5 = this.storageFile.MD5;
            return FileStorages.GetUserFileImageThumbnailPath(md5[0], md5[1], md5[2], md5[3], md5[4], md5[5], StorageID, "{0}x{1}.config".FormatWith(width, height));
        }

        private const string inlines = "jpg,jpeg,gif,png,bmp,txt,html,htm";

        private string contentDisposition;

        /// <summary>
        /// 文档浏览显示格式。
        /// </summary>
        public string ContentDisposition
        {
            get
            {
                if(contentDisposition == null)
                {
                    contentDisposition = inlines.IndexOf(this.Extension) != -1 ? "inline;" : "attachment;";
                    contentDisposition += "filename=" + HttpUtility.UrlEncode(FileName);
                }
                return contentDisposition;
            }
        }
    }
}

